package homework3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class LineCount {

	static int count=0;
	static int grandtotal=0;
	static int fileCount=0;

	public static void main(String args[]){

	    if ( args == null || args.length <1 ){
			System.exit(1);
	    }else {
			for (String file:args){

				if( IsExist(file) ){
					fileCount++;
					System.out.printf("%4d %s\n",ReadFile(file), file);
				}else {
					System.out.println("ERROR: couldn't open " + file);
				}
			}

			//Print Summary
			System.out.println("");
			System.out.println(fileCount + (fileCount<=1?" class, ":" classes, ") + grandtotal + (grandtotal<=1?" line of code":" lines of code"));
	    }
	}

	public static boolean IsExist(String name){
	    File f = new File(name);
	    return f.exists();
	}

	public static int ReadFile(String name){
			String line;
			count = 0;

			try{

			FileReader input = new FileReader(name);
			BufferedReader bufRead = new BufferedReader(input);

			line = bufRead.readLine();
			count++;
			grandtotal++;

			isLegitLine(line);

			while( line != null ){

				line=bufRead.readLine();

				if (isLegitLine(line)) {
					count++;
					grandtotal++;
				}

			}

			bufRead.close();

		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println("Usage: java ReadFile filename\n");
		}catch (IOException e){
			e.printStackTrace();
		}

		return count;
	}

	public static boolean isLegitLine(String line){

		if (line == null) return false;

		line = line.replaceAll("\\s","");	//remove space
		line = line.replace("{","");
		line = line.replace("}","");
		line = line.replace("/*","");
		line = line.replace("/**","");
		line = line.replace("*/","");
		line = line.replace("*","");
		line = line.replace("//","");

		// After moving above characters, if line still has other chars, it's a legit line.
		if(line.length()>0)	return true;

		return false;


	}

}

